<template>
	<yingbing-audio
	ref="audio"
	autoplay
	mode="background"
	:src="src"
	:poster="poster"
	:title="title"
	:lyric="lyric"
	:lyricConfig="lyricConfig"
	:shareConfig="shareConfig"
	@lyricChange="lyricChange"
	@ended="handleEnded"
	@canplay="handleCanplay"
	@play="handlePlay"
	@pause="handlePause"
	@error="handleError"
	@timeUpdate="handleTimeUpdate"
	></yingbing-audio>
</template>
<script>
	import appMixin from '@/common/mixin/app.js'
	let ob = null
	let debug = null
	export default {
		mixins: [appMixin],
		computed: {
			lyricConfig () {
				return {
					mode: this.lyricShow ? 'overall' : 'hidden',
					fillColor: this.skinColor.color_theme_1,
					strokeColor: this.skinColor.color_1,
					offset: uni.getSystemInfoSync().windowBottom + uni.upx2px(20)
				}
			},
			shareConfig () {
				return {
					shareUrl: this.currentSong?.shareUrl || '',
					albumName: this.currentAlbum?.title || '',
					singer: this.currentSong?.creator || this.currentAlbum?.creator || (this.currentSong ? this.app.$business.filterSource(this.currentSong.source).title : '')
				}
			},
			src () {
				return this.currentSong?.src || ''
			},
			title () {
				return this.currentSong?.title || this.currentAlbum?.title || ''
			},
			poster () {
				return this.currentSong?.cover || this.currentAlbum?.cover || ''
			},
			lyric () {
				return this.currentSong?.lyrics || []
			},
			lyricShow () {
				return this.$store.getters['audio/getLyricShow']
			},
			playList () {
				return this.$store.getters['audio/getPlayList']
			},
			randomPlayList () {
				return this.$store.getters['audio/getRandomPlayList']
			},
			currentAlbum () {
				return this.$store.getters['audio/getCurrentAlbum']
			},
			currentPage () {
				return this.$store.getters['audio/getCurrentPage']
			},
			currentPaging () {
				return this.$store.getters['audio/getCurrentPaging']
			},
			currentIsLastPage () {
				return this.$store.getters['audio/getCurrentIsLastPage']
			},
			paused () {
				return this.$store.getters['audio/getPaused']
			},
			playMode () {
				return this.$store.getters['audio/getPlayMode']
			},
			currentSong () {
				return this.$store.getters['audio/getCurrentSong']
			},
			isDebug () {
				return this.$store.getters['debug/get']
			}
		},
		beforeCreate() {
			uni.$on('debug', data => {
				debug && debug.show()
			})
			uni.$on('scircle', data => {
				ob.show()
			})
			uni.$on('goPlayer', data => {
				ob.hide()
				getApp().globalData.$Router.push({
					path: '/pages/audio/player',
					animationType: 'fade-in'
				})
			})
			uni.$on('seekSong', time => {
				this.seek(time)
			})
			uni.$on('play', () => {
				this.play()
			})
			uni.$on('pause', () => {
				this.pause()
			})
		},
		beforeDestroy () {
			ob.close()
			ob = null
			this.$store.dispatch('audio/destroy')
			debug && debug.close()
			debug = null
			uni.$off('debug')
			uni.$off('scircle')
			uni.$off('goPlayer')
			uni.$off('seekSong')
			uni.$off('play')
			uni.$off('pause')
			if ( this.nextTimer ) {
				clearTimeout(this.nextTimer)
				this.nextTimer = null
			}
		},
		created () {
			ob = getApp().globalData.$nativeUI.scircle({
				width: uni.upx2px(60),
				height: uni.upx2px(60),
				left: uni.getSystemInfoSync().windowWidth - 50,
				top: uni.getSystemInfoSync().windowHeight - 60,
				border: 5,
				touch: true,
				dark: this.skinMode == 'night',
				func: (e) => {
					// getApp().globalData.$dom.control({
					// 	x: e.left,
					// 	y: e.top
					// }).then(() => {
					// 	ob.show()
					// })
					ob.hide()
					getApp().globalData.$Router.push({
						path: '/pages/audio/player',
						animationType: 'fade-in'
					})
				}
			})
			ob.show();
			if ( this.isDebug ) {
				debug = getApp().globalData.$nativeUI.scircle({
					width: uni.upx2px(200),
					height: uni.upx2px(80),
					left: uni.getSystemInfoSync().windowWidth - uni.upx2px(200),
					top: uni.getSystemInfoSync().windowHeight - uni.upx2px(200),
					border: 5,
					touch: true,
					text: '调试',
					dark: this.skinMode == 'night',
					func: (e) => {
						debug.hide()
						getApp().globalData.$Router.push({
							path: '/modules/debug',
							animationType: 'slide-in-right'
						})
					}
				})
				debug.show();
			}
		},
		methods: {
			getDetail () {
				if ( this.nextTimer ) {
					clearTimeout(this.nextTimer)
					this.nextTimer = null
				}
				let song = this.currentSong
				if ( song.source != 'local' ) {
					this.app.$api.getSingleDetail(song).then(res => {
						if ( res.code == this.app.$config.ERR_OK ) {
							song = Object.assign({}, song, res.data?.data || {})
						}
						if ( !song.shareUrl ) song.shareUrl = res.requestUrl
						let tag = this.app.$business.getTag(song)
						song.tag = [...new Set(song.tag.concat(tag))]
						if ( !song.isPay && song.src ) {
							this.$store.commit('audio/setCurrentSong', song)
							if ( this.$store.getters['app/getFootmark'] ) {
								if ( this.currentAlbum && this.app.$config.audioTypes.gather[this.currentAlbum.type] ) {
									this.$store.dispatch(
										'record/add',
										Object.assign({}, this.currentAlbum, {
											record: {
												params: song,
												currentPage: this.currentPage,
												paging: this.currentPaging,
												isLastPage: this.currentIsLastPage
											}
										})
									)
								} else if ( this.app.$config.audioTypes.single[song.type] ) {
									this.$store.dispatch('record/add', song)
								}
							} 
						} else {
							uni.showToast({
								title: '付费' + this.app.$business.getType(song.type) + '请支持正版，2秒后继续播放',
								icon: 'none',
								duration: 2000
							})
							this.nextTimer = setTimeout(() => {
								this.$store.dispatch('audio/next')
							}, 2000)
						}
					})
				} else {
					if ( this.$store.getters['app/getFootmark'] ) {
						this.$store.dispatch('record/add', song)
					}
				}
			},
			getCache (id) {
				const caches = this.$store.getters['cache/get']
				const index = caches.findIndex(cache => cache.parentId == id)
				if ( index > -1 ) {
					const src = plus.io.convertLocalFileSystemURL(caches[index].src);
					const file = plus.android.newObject('java.io.File', src);
					if ( plus.android.invoke(file, 'exists') ) {
						return src
					} else {
						dispatch('cache/removeCache', caches[index].id)
					}
				}
				return null
			},
			getRandomPlayList () {
				let randomList = this.randomPlayList.filter(rnd => this.playList.findIndex(ply => ply.id == rnd.id) > -1 )
				let otherList = this.playList.filter(rnd => this.randomPlayList.findIndex(ply => ply.id == rnd.id) == -1 )
				let len = otherList.length
				let min = 0;
				let max = len - 1;
				let arr = [];
				while ( arr.length < len ) {
					let value = Math.floor(Math.random() * (max - min + 1)) + min;
					if ( arr.indexOf(value) == -1 ) {
						arr.push(otherList[value])
					}
				}
				return randomList.concat(arr)
			},
			lyricChange (e) {
				this.$store.commit('audio/setCurrentLyricIndex', e.index)
				this.$store.commit('audio/setCurrentLyricTitle', e.title)
			},
			handleCanplay (e) {
				this.$store.commit('audio/setDuration', e.duration)
			},
			handlePlay () {
				this.$store.commit('audio/setPaused', false)
			},
			handlePause () {
				this.$store.commit('audio/setPaused', true)
			},
			handleStop () {
				this.$store.dispatch('audio/stop')
			},
			handleEnded () {
				this.$store.dispatch('audio/next')
			},
			handleError () {
				this.app.$nativeUI.alert({
					title: '错误提示',
					content: '音频播放失败！是否删除并继续播放',
					dark: this.skinMode == 'night',
					success: (res) => {
						if ( res.confirm ) {
							this.$store.dispatch('audio/removeSong', this.currentSong.id)
							this.$nextTick(function () {
								this.$store.dispatch('audio/next')
							})
						}
					}
				})
			},
			handleTimeUpdate (e) {
				this.$store.commit('audio/setCurrentTime', e.currentTime)
			},
			seek (time) {
				this.$refs.audio.seek(time)
			},
			play () {
				this.$refs.audio.play()
			},
			pause () {
				this.$refs.audio.pause()
			},
			stop () {
				this.$refs.audio.stop()
			}
		},
		watch: {
			currentSong (newVal, oldVal) {
				if ( newVal && newVal.id != oldVal?.id ) { this.getDetail() }
			},
			playList (newVal, oldVal) {
				this.$store.commit('audio/setRandomPlayList', this.getRandomPlayList())
			},
			skinMode (newVal) {
				ob && ob.reset({
					dark: newVal == 'night'
				})
				debug && debug.reset({
					dark: newVal == 'night'
				})
			},
			isDebug (newVal) {
				if ( newVal ) {
					debug = getApp().globalData.$nativeUI.scircle({
						width: uni.upx2px(200),
						height: uni.upx2px(80),
						left: uni.getSystemInfoSync().windowWidth - uni.upx2px(200),
						top: uni.getSystemInfoSync().windowHeight - uni.upx2px(200),
						border: 5,
						touch: true,
						text: '调试',
						dark: this.skinMode == 'night',
						func: (e) => {
							debug.hide()
							getApp().globalData.$Router.push({
								path: '/modules/debug',
								animationType: 'slide-in-right'
							})
						}
					})
					debug.show();
				} else {
					debug && debug.close()
					debug = null
				}
			}
		}
	}
</script>

<style>

</style>
